import pandas as pd


def extract_features(file_path):
    # 加载数据
    df = pd.read_csv(file_path)

    # 用户
    # 计算用户在平台的总交互次数
    total_interactions = df.groupby('user_id').size().reset_index(name='总交互次数')

    # 将 time_stamp 转换为日期格式
    df['time_stamp'] = pd.to_datetime(df['time_stamp'], format='%m%d').dt.strftime('%m-%d')

    # 计算用户对不同【商品、品类、品牌、商家】的交互次数
    user_item_interactions = df.groupby(['user_id', 'item_id']).size().reset_index(name='商品交互次数')
    user_cat_interactions = df.groupby(['user_id', 'cat_id']).size().reset_index(name='品类交互次数')
    user_brand_interactions = df.groupby(['user_id', 'brand_id']).size().reset_index(name='品牌交互次数')
    user_merchant_interactions = df.groupby(['user_id', 'merchant_id']).size().reset_index(name='商家交互次数')

    # 计算用户进行【点击、加购物车、购买、收藏】的次数
    action_counts = df.groupby(['user_id', 'action_type']).size().unstack(fill_value=0)
    action_counts.columns = ['点击次数', '加购物车次数', '购买次数', '收藏次数']

    # 计算用户的购买率（修改部分）
    total_actions = df.groupby('user_id').size()
    purchase_actions = df[df['action_type'] == 2].groupby('user_id').size()
    purchase_rate = (purchase_actions / total_actions).reset_index(name='购买率')
    purchase_rate['购买率'] = purchase_rate['购买率'].fillna(0)  # 用0填充NaN值


    # 合并结果
    result = total_interactions
    for df_to_merge in [user_item_interactions, user_cat_interactions,
                        user_brand_interactions, user_merchant_interactions, action_counts, purchase_rate]:
        result = pd.merge(result, df_to_merge, on='user_id', how='left')

    # 填充所有NaN值为0（对于没有交互记录的情况）
    result = result.fillna(0)


    return result


# 指定文件路径
file_path = '../balanced_data.csv'
# 提取特征
features_result = extract_features(file_path)

columns_to_drop = ['item_id', 'cat_id', 'brand_id']

# 删除指定列
features_result = features_result.drop(columns_to_drop, axis=1)

print(features_result.head())

print(f"去重前行数: {len(features_result)}")
features_result = features_result.drop_duplicates()
print(f"去重后行数: {len(features_result)}")
# 保存结果，指定编码为 utf-8-sig
csv_path = '用户data_features.csv'
features_result.to_csv(csv_path, index=False, encoding='utf-8-sig')